<?php
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
/*--------------------------------------------------------------------------------------
 Class::RoleAdmin
 Created by Duleepa Wijayawardhana
 August 22, 2005

 Description: Contains the admin methods for the Role System.
 Documentation for the Role System is available at:
 http://staff.bioware.com/wiki/index.html?page=RoleSystemMain&wiki=websystems&action=view
 
 --------------------------------------------------------------------------------------*/
class RoleAdmin extends Role
{
    //This private variable sets whether this user is a super-administrator
    private $bIsAdmin;

    public $aErrors;
    public $aMessages;
        
    /*---------------------------------------------------------------------------------
      void __construct ()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Class constructor
      ---------------------------------------------------------------------------------*/
    public function __construct()
    {
        //Call the protected Roles as we want to have access to the logged in user roles
        //for permissioning in doing stuff.
        $this->GetMyRoles();
        $this->GetMyGlobalActions();
        
        //Check and set the Admin setting
        $this->IsUserAdmin();
        
        $this->Audit = new Audit;
        
    }

    /*---------------------------------------------------------------------------------
      array GetRoleDefinitionTypes()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of distinct role Definition types
      ---------------------------------------------------------------------------------*/
    public function GetRoleDefinitionTypes()
    {
        $sql = "SELECT DISTINCT(description)
		FROM roleDefinition";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            for ($i=0; $i<count($aResult); $i++)
            {
                $aReturn[]=$aResult[$i]["description"];
            }
        }
        
        return $aReturn;
    }
    /*---------------------------------------------------------------------------------
      array GetRoleDefinitionsByType($sType)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of defintions of  roleDefinitionType
      
      Returns:
      -1 => No Type given
      -2 => no results
      ---------------------------------------------------------------------------------*/
    public function GetRoleDefinitionsByType($sType)
    {
        //If not type
	if ($sType=="")
	{
	    $this->aErrors[] = "no role type specified";
	    return -1;
	}
        
        $sql="SELECT ID, name, code, description
            FROM roleDefinition
            WHERE description='".$sType."'
            ORDER BY name ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role definitions found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleDefinitionByID($nID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns a roleDefintion by nID
      
      Returns:
      -1 => No ID given
      -2 => no results
      ---------------------------------------------------------------------------------*/
    public function GetRoleDefinitionByID($nID)
    {
        //If not type
	if ((int)$nID < 1)
	{
	    $this->aErrors[] = "no role definition ID specified";
	    return -1;
	}
        
        $sql = "SELECT ID, name, code, description
		FROM roleDefinition
		WHERE ID='$nID'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role definition found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleTypes()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleTypes that a role can belong to.
      
      Returns:
      -1 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleTypes()
    {
        
        $sql="SELECT *
            FROM roleType
            ORDER BY name ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role types found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleGlobalActions()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns all global actions available to roles
      
      Returns:
      -1 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleGlobalActions()
    {
        
        $sql="SELECT rGA.ID, rGA.roleID, rGA.actionID, rA.name as actionName, rA.type as actionType, 
            rD.name as roleDefinition, rT.name as roleType, rA.groupID
            FROM roleGlobalAction rGA
            LEFT JOIN roleAction rA ON rA.ID=rGA.actionID
            LEFT JOIN role r ON r.ID=rGA.roleID
            LEFT JOIN roleDefinition rD ON rD.ID=r.roleDefinitionID
            LEFT JOIN roleType rT ON rT.ID=r.roleTypeID
            ORDER BY rA.groupID, rA.name, rD.name ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role global actions found";
            return -1;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleGlobalActionByID($nID)
      Created by Duleepa Wijayawardhana
      August 24, 2005
      
      Description: Returns an array of info on GlobalAction by ID.
      
      Returns:
      -1 => No ID
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleGlobalActionByID($nID)
    {
        if (!$nID || (int)$nID < 1)
        {
	    $this->aErrors[] = "no role global action ID specified";
            return -1;
        }
        
        $sql="SELECT rGA.ID, rGA.roleID, rGA.actionID, rA.name as actionName, rA.type as actionType,
            rD.name as roleDefinition, rT.name as roleType, r.roleTypeID
            FROM roleGlobalAction rGA
            LEFT JOIN roleAction rA ON rA.ID=rGA.actionID
            LEFT JOIN role r ON r.ID=rGA.roleID
            LEFT JOIN roleDefinition rD ON rD.ID=r.roleDefinitionID
            LEFT JOIN roleType rT ON rT.ID=r.roleTypeID
            WHERE rGA.ID='".$nID."'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role global action found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleActions()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleActions.
      
      Returns:
      -1 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleActions()
    {
        
        $sql="SELECT ID, name, type, groupID
            FROM roleAction
            ORDER BY name ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role actions found";
            return -1;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleActionsByGroupID($sGroupID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleActions by string GroupID.
      
      Returns:
      -1 => No Results
      -2 => No Group passed in
      ---------------------------------------------------------------------------------*/
    public function GetRoleActionsByGroupID($sGroupID)
    {
        if ($sGroupID == "")
        {
	    $this->aErrors[] = "no group ID specified";
            return -2;
        }
        
        $sql="SELECT ID, name, type, groupID
            FROM roleAction
            WHERE groupID='".$sGroupID."'
            ORDER BY name ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "no role actions found";
            return -1;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleActionGroupIDs($sGroupID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleActions GroupIDs.
      
      Returns:
      -1 => No Results
      -2 => No Group passed in
      ---------------------------------------------------------------------------------*/
    public function GetRoleActionGroupIDs()
    {
       
        $sql="SELECT distinct(groupID)
            FROM roleAction
            ORDER BY groupID ASC";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            for ($i=0; $i<count($aResult); $i++)
            {
                $aReturn[]=$aResult[$i]["groupID"];
            }
            return $aReturn;
        }
        else
        {
	    $this->aErrors[] = "no role action group IDs found";
            return -1;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleActionByID($nID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of info on action by ID.
      
      Returns:
      -1 => No ID
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleActionByID($nID)
    {
        if (!$nID || $nID < 1)
        {
	    $this->aErrors[] = "no role action ID specified";
            return -1;
        }
        
        $sql="SELECT ID, name, type, groupID
            FROM roleAction
            WHERE ID='".$nID."'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "role action not found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleTypeByID($mID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of information for a role Type based on mID.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleTypeByID($mID)
    {
        //No ID
        if ($mID=="")
        {
	    $this->aErrors[] = "no role type ID specified";
            return -1;
        }
        
        
        if (is_numeric($mID) && $mID>0)
        {
            $sWhereString=" ID='".$mID."'";
        }
        elseif (is_string($mID) && $mID!="")
        {
            $sWhereString=" stringID='".$mID."'";
        }
        
        $sql="SELECT *
            FROM roleType
            WHERE ".$sWhereString;
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
	    $this->aErrors[] = "role type not found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleByID($mID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of information for a role based on mID. mID can be a
      single integer or an array of roles, if an array is passed in then  it will
      return a multi-dimensional array
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleByID($mID)
    {
        if (!is_array($mID))
        {
            if (!$mID || $mID<1)
            {
		$this->aErrors[] = "no role ID specified";
                return -1;
            }
            
            $sIDCheck = "r.ID='".$mID."'";
            $bFetchArray=false;
        }
        else
        {
            $sIDStr = implode(",", $mID);
            $sIDCheck = "r.ID IN (".$sIDStr.")";
            $bFetchArray=true;
        }
        
        
        $sql="SELECT r.ID, r.notes, r.roleTypeID, r.roleDefinitionID, r.roleStringID, rD.description as roleDefinitionType,
            rD.name as roleName, rT.name as roleType
            FROM role r
            LEFT JOIN roleDefinition rD ON rD.ID=r.roleDefinitionID
            LEFT JOIN roleType rT ON rT.ID=r.roleTypeID
            WHERE ".$sIDCheck;
        if ($bFetchArray)
        {
            $aResult=db_fetch_array(db_query($sql));
        }
        else
        {
            $aResult=db_fetch_result(db_query($sql));
        }
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "role not found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleInfoByTypeID($nID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of role based on nTypeID (roleTypeID.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleInfoByTypeID($nTypeID)
    {
        if (!$nTypeID || $nTypeID<1)
        {
    	    $this->aErrors[] = "no role type ID specified";
            return -1;
        }
        
        $sql="SELECT r.ID, r.notes, rT.name as roleType, r.roleTypeID, rD.name as roleDefinition, r.roleDefinitionID, r.roleStringID
            FROM role r
            LEFT JOIN roleType rT ON rT.ID=r.roleTypeID
            LEFT JOIN roleDefinition rD ON rD.ID=r.roleDefinitionID
            WHERE r.roleTypeID='".$nTypeID."'";
        
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "role type not found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleInfoByRoleID($mID)
      Created by Jesse van Herk
      Feb 21, 2006
      
      Description: Returns an array of role info/details based on the given nID

      Arguments: 
	    $aRoleIDs - array of role IDs to retrieve info for
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleInfoByRoleID($aRoleIDs)
    {
	if(!is_array($aRoleIDs) || count($aRoleIDs) < 1)
        {
    	    $this->aErrors[] = "no role IDs specified";
            return -1;
        }

	$sRoleIDs = join(",", $aRoleIDs);
        
        $sql="SELECT r.ID, r.notes, rT.name as roleType, r.roleTypeID, rD.name as roleDefinition, r.roleDefinitionID, r.roleStringID
            FROM role r
            LEFT JOIN roleType rT ON rT.ID=r.roleTypeID
            LEFT JOIN roleDefinition rD ON rD.ID=r.roleDefinitionID
            WHERE r.ID IN (" . $sRoleIDs . ")
	    ORDER BY r.ID";
        
        $aResult = db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no roles found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleRelationshipTypes()
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleRelationship types.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleRelationshipTypes()
    {
        
        $sql="SELECT DISTINCT(relationshipType)
            FROM roleRelationship
            ORDER BY relationshipType";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            for ($i=0; $i<count($aResult); $i++)
            {
                $aReturn[]=$aResult[$i]["relationshipType"];
            }
            
            return $aReturn;
        }
        else
        {
    	    $this->aErrors[] = "no role relationships found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetUserRelationshipTypes()
      Created by Jesse van Herk <jesse@bioware.com> 
	March 02, 2006
      
      Description: Returns an array of userRelationship types.
      
      Returns:
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetUserRelationshipTypes()
    {
        
        $sql="SELECT DISTINCT(relationshipType)
            FROM userRelationship
            ORDER BY relationshipType";
        $aResult = db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            for ($i = 0; $i < count($aResult); $i++)
            {
                $aReturn[]=$aResult[$i]["relationshipType"];
            }
            
            return $aReturn;
        }
        else
        {
    	    $this->aErrors[] = "no user relationship types found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleTypeRelationshipTypes()
      Created by Duleepa Wijayawardhana
      August 24, 2005
      
      Description: Returns an array of roleTypeRelationship types.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleTypeRelationshipTypes()
    {
        
        $sql="SELECT DISTINCT(relationshipType)
            FROM roleTypeRelationship
            ORDER BY relationshipType";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            for ($i=0; $i<count($aResult); $i++)
            {
                $aReturn[]=$aResult[$i]["relationshipType"];
            }
            
            return $aReturn;
        }
        else
        {
    	    $this->aErrors[] = "no role type relationship types found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleRelationshipsByType($nID[, array aObjectInfo])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleRelationships based on string type.
      
      You can also specify an array aObjectInfo
      "jointable" => table to join objectID to
      "joinfield" => field name in join table to join to
      "returnfield" => field to return.
      "returnas" => field to return as
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleRelationshipsByType($sType, $aObjectInfo=NULL)
    {
        if ($sType=="" || !$sType)
        {
    	    $this->aErrors[] = "no role relationship type specified";
            return -1;
        }
        
        if (is_array($aObjectInfo))
        {
            if ($aObjectInfo["jointable"]!="" && $aObjectInfo["joinfield"] && $aObjectInfo["returnfield"])
            {
                $sObjectJoin="LEFT JOIN ".$aObjectInfo["jointable"]." objectjoin ON objectjoin.".$aObjectInfo["joinfield"]."=rR.objectID";
                $sObjectReturn=", objectjoin.".$aObjectInfo["returnfield"];
                if ($aObjectInfo["returnas"]!="")
                {
                    $sObjectReturn.=" as ".$aObjectInfo["returnas"];
                }
            }
            
            
        }
        
        switch ($aObjectInfo["orderby"])
        {
            case "actiontype":
                $sOrder=" ORDER BY rA.type, rR.primaryRoleID ASC";
                break;
            case "secondaryrole":
                $sOrder=" ORDER BY rR.secondaryRoleID ASC";
                break;
            case "primaryrole":
            case "":
            default:
                $sOrder=" ORDER BY rR.primaryRoleID ASC";
                break;
        }
        
        $sql="SELECT rR.ID, rR.primaryRoleID, rR.secondaryRoleID, rD1.name as primaryRoleDefinition,
            rT1.name as primaryRoleType, rT2.name as secondaryRoleType,
            rD2.name as secondaryRoleDefinition, rA.name as roleAction, rA.type as roleType, rR.objectID, rR.actionID".$sObjectReturn."
            FROM roleRelationship rR
            LEFT JOIN role r1 ON r1.ID=rR.primaryRoleID
            LEFT JOIN role r2 ON r2.ID=rR.secondaryRoleID
            LEFT JOIN roleDefinition rD1 ON rD1.ID=r1.roleDefinitionID
            LEFT JOIN roleDefinition rD2 ON rD2.ID=r2.roleDefinitionID
            LEFT JOIN roleType rT1 ON rT1.ID = r1.roleTypeID
            LEFT JOIN roleType rT2 ON rT2.ID = r2.roleTypeID
            LEFT JOIN roleAction rA ON rA.ID=rR.actionID
            ".$sObjectJoin."
            WHERE rR.relationshipType='".$sType."'
            ".$sOrder;
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no role relationships found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetUserRelationshipsByType($nID[, array aObjectInfo])
      Created by Jesse van Herk <jesse@bioware.com> 
      March 02, 2006
      
      Description: Returns an array of userRelationships based on string type.
      
      You can also specify an array aObjectInfo
      "jointable" => table to join objectID to
      "joinfield" => field name in join table to join to
      "returnfield" => field to return.
      "returnas" => field to return as
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetUserRelationshipsByType($sType, $aObjectInfo=NULL)
    {
        if ($sType=="" || !$sType)
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -1;
        }
        
        if (is_array($aObjectInfo))
        {
            if ($aObjectInfo["jointable"]!="" && $aObjectInfo["joinfield"] && $aObjectInfo["returnfield"])
            {
                $sObjectJoin="LEFT JOIN ".$aObjectInfo["jointable"]." objectjoin ON objectjoin.".$aObjectInfo["joinfield"]."=rR.objectID";
                $sObjectReturn=", objectjoin.".$aObjectInfo["returnfield"];
                if ($aObjectInfo["returnas"]!="")
                {
                    $sObjectReturn.=" as ".$aObjectInfo["returnas"];
                }
            }
            
            
        }
        
        switch ($aObjectInfo["orderby"])
        {
            case "actiontype":
                $sOrder=" ORDER BY rA.type, uR.primaryUsername ASC";
                break;
            case "secondaryusername":
                $sOrder=" ORDER BY uR.secondaryUsername ASC";
                break;
            case "primaryusername":
            case "":
            default:
                $sOrder=" ORDER BY uR.primaryUsername ASC";
                break;
        }
        
        $sql="SELECT uR.ID, uR.primaryUsername, uR.secondaryUsername,
            rA.name as userAction, rA.type as roleType, uR.objectID, uR.actionID".$sObjectReturn."
            FROM userRelationship uR
            LEFT JOIN roleAction rA ON rA.ID=uR.actionID
            ".$sObjectJoin."
            WHERE uR.relationshipType='".$sType."'
            ".$sOrder;
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no user relationships found";
            return -2;
        }
    }

    /*---------------------------------------------------------------------------------
      array GetRoleTypeRelationshipsByType($sType)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleTypeRelationships based on string type.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleTypeRelationshipsByType($sType)
    {
        if ($sType=="" || !$sType)
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -1;
        }
        
        $sql="SELECT rR.ID, rR.primaryRoleID, rR.roleTypeID, rD1.name as primaryRoleDefinition,
        rT.name as roleType, rA.name as roleAction, rR.actionID
            FROM roleTypeRelationship rR
            LEFT JOIN role r1 ON r1.ID=rR.primaryRoleID
            LEFT JOIN roleDefinition rD1 ON rD1.ID=r1.roleDefinitionID
            LEFT JOIN roleType rT ON rT.ID=rR.roleTypeID
            LEFT JOIN roleAction rA ON rA.ID=rR.actionID
            WHERE rR.relationshipType='".$sType."'";
        $aResult=db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no role type relationships found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleTypeRelationshipByID($nID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of roleTypeRelationship based on ID.
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleTypeRelationshipByID($nID)
    {
        if ($nID<1 || !$nID)
        {
    	    $this->aErrors[] = "no relationship ID specified";
            return -1;
        }
        
        $sql="SELECT rR.ID, rR.primaryRoleID, rR.roleTypeID, rD1.name as primaryRoleDefinition,
        rT.name as roleType, rA.name as roleAction, rR.actionID, r1.roleTypeID as primaryRoleTypeID, rR.relationshipType
            FROM roleTypeRelationship rR
            LEFT JOIN role r1 ON r1.ID=rR.primaryRoleID
            LEFT JOIN roleDefinition rD1 ON rD1.ID=r1.roleDefinitionID
            LEFT JOIN roleType rT ON rT.ID=rR.roleTypeID
            LEFT JOIN roleAction rA ON rA.ID=rR.actionID
            WHERE rR.ID='".$nID."'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no role type relationships found";
            return -2;
        }
    }
    /*---------------------------------------------------------------------------------
      array GetRoleRelationshipByID($nID)
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Returns an array of info on a roleRelationship by ID
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetRoleRelationshipByID($nID)
    {
        if ($nID<1 || !$nID)
        {
    	    $this->aErrors[] = "no relationship ID specified";
            return -1;
        }
        
        $sql="SELECT rR.ID, rR.primaryRoleID, rR.secondaryRoleID,
        rD1.name as primaryRoleDefinition, rD2.name as secondaryRoleDefinition, rA.name as roleAction, rR.actionID,
        r1.roleTypeID as primaryRoleTypeID, r2.roleTypeID as secondaryRoleTypeID, rR.relationshipType, rR.objectID
            FROM roleRelationship rR
            LEFT JOIN role r1 ON r1.ID=rR.primaryRoleID
            LEFT JOIN role r2 ON r2.ID=rR.secondaryRoleID
            LEFT JOIN roleDefinition rD1 ON rD1.ID=r1.roleDefinitionID
            LEFT JOIN roleDefinition rD2 ON rD2.ID=r2.roleDefinitionID
            LEFT JOIN roleAction rA ON rA.ID=rR.actionID
            WHERE rR.ID='".$nID."'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no role relationships found";
            return -2;
        }
    }
    
    /*---------------------------------------------------------------------------------
      array GetUserRelationshipByID($nID)
      Created by Jesse van Herk <jesse@bioware.com> 
      August 22, 2005
      
      Description: Returns an array of info on a userRelationship by ID
      
      Returns:
      -1 => No ID Passed in
      -2 => No Results
      ---------------------------------------------------------------------------------*/
    public function GetUserRelationshipByID($nID)
    {
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no user relationship ID specified";
            return -1;
        }
        
        $sql = "SELECT uR.ID, uR.primaryUsername, uR.secondaryUsername,
		rA.name as roleAction, uR.actionID,
		uR.relationshipType, uR.objectID
		FROM userRelationship uR
		LEFT JOIN roleAction rA ON rA.ID=uR.actionID
		WHERE uR.ID='".$nID."'";
        $aResult=db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
        else
        {
    	    $this->aErrors[] = "no user relationships found";
            return -2;
        }
    }
    
    /*---------------------------------------------------------------------------------
      int SetRoleGlobalAction(array aInfo[, int nID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a roleGlobalAction based on info in array aInfo. If optional nID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleGlobalAction
      -4 => unsuccessful update of a roleGlobalAction
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleGlobalAction($aInfo, $nID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set a role global action";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no action info specified";
            return -2;
        }
       
        
        if ($nID!=NULL && $nID>0)
        {
            $sql="UPDATE roleGlobalAction SET
                roleID='".$aInfo["roleID"]."',
                actionID='".$aInfo["actionID"]."'
                WHERE ID='".$nID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nID,
                    "type" => "roleGlobalAction",
                    "action" => "edit",
                    "comment" => "roleID: ".$aInfo["roleID"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nID;
            }
            else
            {
		$this->aErrors[] = "failed to update role global action";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleGlobalAction SET
                roleID='".$aInfo["roleID"]."',
                actionID='".$aInfo["actionID"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleGlobalAction",
                    "action" => "create",
                    "comment" => "roleID: ".$aInfo["roleID"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "failed to insert role global action";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRoleTypeRelationship(array aInfo[, int nID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a roleType Relationship based on info in array aInfo. If optional nID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleTypeRelationship
      -4 => unsuccessful update of a roleTypeRelationship
      -5 => No relationshipType offered
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleTypeRelationship($aInfo, $nID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set role type relationships";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no relationship info specified";
            return -2;
        }
        
        if ($aInfo["relationshipType"]=="")
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -5;
        }
        
        if ($nID!=NULL && $nID>0)
        {
            $sql="UPDATE roleTypeRelationship SET
                primaryRoleID='".$aInfo["primaryRoleID"]."',
                roleTypeID='".$aInfo["roleTypeID"]."',
                relationshipType='".$aInfo["relationshipType"]."',
                actionID='".$aInfo["actionID"]."'
                WHERE ID='".$nID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nID,
                    "type" => "roleTypeRelationship",
                    "action" => "edit",
                    "comment" => "primaryRoleID: ".$aInfo["primaryRoleID"]."|roleTypeID: ".$aInfo["roleTypeID"]."|relationshipType: ".$aInfo["relationshipType"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nID;
            }
            else
            {
		$this->aErrors[] = "could not update relationship type";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleTypeRelationship SET
                primaryRoleID='".$aInfo["primaryRoleID"]."',
                roleTypeID='".$aInfo["roleTypeID"]."',
                relationshipType='".$aInfo["relationshipType"]."',
                actionID='".$aInfo["actionID"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleTypeRelationship",
                    "action" => "create",
                    "comment" => "primaryRoleID: ".$aInfo["primaryRoleID"]."|roleTypeID: ".$aInfo["roleTypeID"]."|relationshipType: ".$aInfo["relationshipType"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert relationship type";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRoleRelationship(array aInfo[, int nID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a role Relationship based on info in array aInfo. If optional nID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleRelationship
      -4 => unsuccessful update of a roleRelationship
      -5 => No relationshipType offered
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleRelationship($aInfo, $nID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set role relationships";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no role relationship info specified";
            return -2;
        }
        
        if ($aInfo["relationshipType"]=="")
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -5;
        }
        
        
        if ($nID!=NULL && $nID>0)
        {
            $sql="UPDATE roleRelationship SET
                primaryRoleID='".$aInfo["primaryRoleID"]."',
                secondaryRoleID='".$aInfo["secondaryRoleID"]."',
                relationshipType='".$aInfo["relationshipType"]."',
                objectID='".$aInfo["objectID"]."',
                actionID='".$aInfo["actionID"]."'
                WHERE ID='".$nID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nID,
                    "type" => "roleRelationship",
                    "action" => "edit",
                    "comment" => "primaryRoleID: ".$aInfo["primaryRoleID"]."|secondaryRoleID: ".$aInfo["secondaryRoleID"]."|relationshipType: ".$aInfo["relationshipType"]."|objectID: ".$aInfo["objectID"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nID;
            }
            else
            {
		$this->aErrors[] = "could not update role relationship";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleRelationship SET
                primaryRoleID='".$aInfo["primaryRoleID"]."',
                secondaryRoleID='".$aInfo["secondaryRoleID"]."',
                objectID='".$aInfo["objectID"]."',
                relationshipType='".$aInfo["relationshipType"]."',
                actionID='".$aInfo["actionID"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleRelationship",
                    "action" => "create",
                    "comment" => "primaryRoleID: ".$aInfo["primaryRoleID"]."|secondaryRoleID: ".$aInfo["secondaryRoleID"]."|relationshipType: ".$aInfo["relationshipType"]."|objectID: ".$aInfo["objectID"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert role relationship";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetUserRelationship(array aInfo[, int nID])
      Created by Jesse van Herk <jesse@bioware.com> 
      March 01, 2006
      
      Description: Sets a user->user Relationship based on info in array aInfo. If optional nID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a userRelationship
      -4 => unsuccessful update of a userRelationship
      -5 => No relationshipType offered
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetUserRelationship($aInfo, $nID=NULL)
    {
        if (!$this->IsGlobalActionAvailableToUser("manage.User.Relationships"))
        {
    	    $this->aErrors[] = "you do not have permission to set user relationships";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no user relationship info specified";
            return -2;
        }
        
        if ($aInfo["relationshipType"] == "")
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -5;
        }
        
	$aInfo['primaryUsername'] = trim($aInfo['primaryUsername']); // remove wacky spaces
	$aInfo['secondaryUsername'] = trim($aInfo['secondaryUsername']); // remove wacky spaces
        
        if ($nID != NULL && $nID > 0)
        {
            $sql="UPDATE userRelationship SET
                primaryUsername='" . $aInfo["primaryUsername"] . "',
                secondaryUsername='" . $aInfo["secondaryUsername"] . "',
                relationshipType='" . $aInfo["relationshipType"] . "',
                objectID='" . $aInfo["objectID"] . "',
                actionID='" . $aInfo["actionID"] . "'
                WHERE ID='" . $nID . "'";
            $nAffectedRows = db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows > 0)
            {
                $aOptions = array(
                    "primaryNumericID" => $nID,
                    "type" => "userRelationship",
                    "action" => "edit",
                    "comment" => "primaryUsername: " . $aInfo["primaryUsername"] . "|secondaryUsername: " . $aInfo["secondaryUsername"] . "|relationshipType: " . $aInfo["relationshipType"] . "|objectID: " . $aInfo["objectID"] . "|actionID: " . $aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nID;
            }
            else
            {
		$this->aErrors[] = "could not update user relationship";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO userRelationship SET
                primaryUsername='" . $aInfo["primaryUsername"] . "',
                secondaryUsername='" . $aInfo["secondaryUsername"] . "',
                objectID='" . $aInfo["objectID"] . "',
                relationshipType='" . $aInfo["relationshipType"] . "',
                actionID='" . $aInfo["actionID"] . "'";
            $nInsertID = db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID > 0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "userRelationship",
                    "action" => "create",
                    "comment" => "primaryUsername: ".$aInfo["primaryUsername"]."|secondaryUsername: ".$aInfo["secondaryUsername"]."|relationshipType: ".$aInfo["relationshipType"]."|objectID: ".$aInfo["objectID"]."|actionID: ".$aInfo["actionID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert user relationship";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRoleAction(array aInfo[, int nActionID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a role Action based on info in array aInfo. If optional nActionID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleAction
      -4 => unsuccessful update of a roleAction
      -5 => Missing Info
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleAction($aInfo, $nActionID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set role actions";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no role action info specified";
            return -2;
        }
        
        if ($aInfo["name"]=="" || $aInfo["type"]=="" || $aInfo["groupID"]=="")
        {
    	    $this->aErrors[] = "no role action name, type, or group ID specified";
            return -5;
        }
        
        if ($nActionID!=NULL && $nActionID>0)
        {
            $sql="UPDATE roleAction SET
                name='".$aInfo["name"]."',
                type='".$aInfo["type"]."',
                groupID='".$aInfo["groupID"]."'
                WHERE ID='".$nActionID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nActionID,
                    "type" => "roleAction",
                    "action" => "edit",
                    "comment" => "name: ".$aInfo["name"]."|type: ".$aInfo["type"]."|groupID: ".$aInfo["groupID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nActionID;
            }
            else
            {
		$this->aErrors[] = "could not update role action";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleAction SET
                name='".$aInfo["name"]."',
                type='".$aInfo["type"]."',
                groupID='".$aInfo["groupID"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleAction",
                    "action" => "create",
                    "comment" => "name: ".$aInfo["name"]."|type: ".$aInfo["type"]."|groupID: ".$aInfo["groupID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert role action";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRoleDefinition(array aInfo[, int nDefID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a role Definition based on info in array aInfo. If optional nDefID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleDefinition
      -4 => unsuccessful update of a roleDefinition
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleDefinition($aInfo, $nDefID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set role definitions";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "norole definition info specified";
            return -2;
        }
        
        if ($nDefID!=NULL && $nDefID>0)
        {
            $sql="UPDATE roleDefinition SET
                name='".$aInfo["name"]."',
                code='".$aInfo["code"]."',
                description='".$aInfo["description"]."'
                WHERE ID='".$nDefID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nDefID,
                    "type" => "roleDefinition",
                    "action" => "edit",
                    "comment" => "name: ".$aInfo["name"]."|code: ".$aInfo["code"]."|description: ".$aInfo["description"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nDefID;
            }
            else
            {
		$this->aErrors[] = "could not update role definition";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleDefinition SET
                code='".$aInfo["code"]."',
                name='".$aInfo["name"]."',
                description='".$aInfo["description"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleDefinition",
                    "action" => "create",
                    "comment" => "name: ".$aInfo["name"]."|code: ".$aInfo["code"]."|description: ".$aInfo["description"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert role definition";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRoleType(array aInfo[, int nTypeID])
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Sets a role type based on info in array aInfo. If optional nTypeID is specified
      then an update instead of an insert is performed
      Only super admins may perform this function
      
      Returns:
      -1 => Not an admin
      -2 => No array of info
      -3 => unsuccessful insert of a roleType
      -4 => unsuccessful update of a roleType
      
      positive on success with insert ID on successful insert or update
    
      ---------------------------------------------------------------------------------*/
    public function SetRoleType($aInfo, $nTypeID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set role types";
            return -1;
        }
        
        //No array of Info
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no role type info specified";
            return -2;
        }
        
        if ($nTypeID!=NULL && $nTypeID>0)
        {
            $sql="UPDATE roleType SET
                maxAllowed='".$aInfo["maxAllowed"]."',
                name='".$aInfo["name"]."',
                stringID='".$aInfo["stringID"]."',
                description='".$aInfo["description"]."'
                WHERE ID='".$nTypeID."'";
            $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffectedRows>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nTypeID,
                    "type" => "roleType",
                    "action" => "edit",
                    "comment" => "maxAllowed: ".$aInfo["maxAllowed"]."|name: ".$aInfo["name"]."|description: ".$aInfo["description"]."|stringID: ".$aInfo["stringID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nTypeID;
            }
            else
            {
		$this->aErrors[] = "could not update role type";
                return -4;
            }
        }
        else
        {
            $sql="INSERT INTO roleType SET
                maxAllowed='".$aInfo["maxAllowed"]."',
                name='".$aInfo["name"]."',
                stringID='".$aInfo["stringID"]."',
                description='".$aInfo["description"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "roleType",
                    "action" => "create",
                    "comment" => "maxAllowed: ".$aInfo["maxAllowed"]."|name: ".$aInfo["name"]."|description: ".$aInfo["description"]."|stringID: ".$aInfo["stringID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert role type";
                return -3;
            }
        }

    }
    /*---------------------------------------------------------------------------------
      int SetRole($aInfo [, int nRoleID] )
      Created by Duleepa Wijayawardhana
      August 22, 2005
      
      Description: Set's a role into the database. If RoleID is specified then an
      update is performed rather than an insert.
      
      aInfo=array
      "roleDefinitionID" => int
      "roleTypeID" => int
      "roleStringID" => string
      
      Return:
      
      -1 => Not An Admin, no permission
      -2 => No Info Array
      -3 => Update did not write to DB
      -4 => Unknown Error.
      -5 => Insert did not write to DB
      
      positive return is successful and the ID of the inserted role or the ID of the
      updated role
      ---------------------------------------------------------------------------------*/
    public function SetRole($aInfo, $nRoleID=NULL)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to set roles";
            return -1;
        }
        
        //If no data passed in
        if (!is_array($aInfo))
        {
    	    $this->aErrors[] = "no role info specified";
            return -2;
        }
        
        //If no role definitionID 
        
        if ($nRoleID==NULL)
        {
            $sql="INSERT INTO role SET
            roleDefinitionID='".$aInfo["roleDefinitionID"]."',
            roleTypeID='".$aInfo["roleTypeID"]."',
            notes='".$aInfo["notes"]."',
            roleStringID='".$aInfo["roleStringID"]."'";
            $nInsertID=db_query($sql, array("getInsertID" => true));
            
            if ($nInsertID>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nInsertID,
                    "type" => "role",
                    "action" => "create",
                    "comment" => "roleDefinitionID: ".$aInfo["roleDefinitionID"]."|roleTypeID: ".$aInfo["roleTypeID"]."|notes: ".$aInfo["notes"]."|roleStringID: ".$aInfo["roleStringID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nInsertID;
            }
            else
            {
		$this->aErrors[] = "could not insert role";
                return -5;
            }
        }
        elseif ($nRoleID>0)
        {
            $sql="UPDATE role SET
            roleDefinitionID='".$aInfo["roleDefinitionID"]."',
            roleTypeID='".$aInfo["roleTypeID"]."',
            notes='".$aInfo["notes"]."',
            roleStringID='".$aInfo["roleStringID"]."'
            WHERE ID='".$nRoleID."'";
            $nAffected=db_query($sql, array("getAffectedRows" => true));
            
            if ($nAffected>0)
            {
                $aOptions=array(
                    "primaryNumericID" => $nRoleID,
                    "type" => "role",
                    "action" => "edit",
                    "comment" => "roleDefinitionID: ".$aInfo["roleDefinitionID"]."|roleTypeID: ".$aInfo["roleTypeID"]."|notes: ".$aInfo["notes"]."|roleStringID: ".$aInfo["roleStringID"]
                    );
                $this->Audit->SetAudit($aOptions, "rolesystem");
                
                //Successful
                return $nRoleID;
            }
            else
            {
		$this->aErrors[] = "could not update role";
                return -3;
            }
        }
        
	$this->aErrors[] = "no role or roledefinition specified";
        return -4;

    }
    /*---------------------------------------------------------------------------------
      void IsUserAdmin()
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Sets the Super Administrator Flag which bypasses all checks
      ---------------------------------------------------------------------------------*/
    public function IsUserAdmin()
    {
        //Set Super Admin Setting
        if ($this->IsGlobalActionAvailableToUser("manage-role-system"))
        {
            $this->bIsAdmin=true;
        }
        else
        {
            $this->bIsAdmin=false;
        }
    }
    
    /*---------------------------------------------------------------------------------
      int RemoveRoleByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a Role based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleByID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove roles";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no role ID specified";
            return -2;
        }
        
        $sql="START TRANSACTION";
        db_query($sql);

	//Remove any entries from role User.  This does NOT need to worry about dates.
        $this->RemoveRoleUserByRoleID($nID);
        
        $sql="SELECT ID FROM roleRelationship WHERE primaryRoleID='".$nID."' OR secondaryRoleID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleRelationshipByID($aResult[$i]["ID"]);
        }
        
        $sql="SELECT ID FROM roleTypeRelationship WHERE primaryRoleID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleTypeRelationshipByID($aResult[$i]["ID"]);
        }
        
        //Remove Role
        $sql="DELETE FROM role WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "role",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        
        $sql="COMMIT";
        db_query($sql);
        
        return 1;
        
    }
    /*---------------------------------------------------------------------------------
      int RemoveRoleUserByRoleID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a Role User based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleUserByRoleID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove users from roles";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no role ID specified";
            return -2;
        }
        
	// this doesn't need to care about dates?
        $sql="SELECT username
            FROM roleUser
            WHERE roleID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            //Delete each user and make sure it is audited
            $this->RemoveRoleByUsername($nID, $aResult[$i]["username"], array("roleGlobal" => "manage-role-system"), "rolesystem");
        }
        
        return 1;
    }
        
    /*---------------------------------------------------------------------------------
      int RemoveRoleTypeByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleType based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleTypeByID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role types";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no role type ID specified";
            return -2;
        }
        
        $sql="START TRANSACTION";
        db_query($sql);
        
        $sql="SELECT ID FROM role WHERE roleTypeID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleByID($aResult[$i]["ID"]);
        }
        
        
        $sql="SELECT ID
            FROM roleTypeRelationship
            WHERE roleTypeID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleTypeRelationshipByID($aResult[$i]["ID"]);
        }
        
        //Now delete the roleType
        $sql="DELETE FROM roleType WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleType",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        
        $sql="COMMIT";
        db_query($sql);
        
        return 1;
    }
    /*---------------------------------------------------------------------------------
      int RemoveRoleDefinitionByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleDefinition based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleDefinitionByID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role definitions";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no role ID specified";
            return -2;
        }
        
        $sql="START TRANSACTION";
        db_query($sql);
        
        $sql="SELECT ID FROM role WHERE roleDefinitionID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleByID($aResult[$i]["ID"]);
        }
        
        //Now delete the roleType
        $sql="DELETE FROM roleDefinition WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleDefinition",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        
        $sql="COMMIT";
        db_query($sql);
        
        return 1;
    }
    /*---------------------------------------------------------------------------------
      int RemoveRoleActionByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleAction based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleActionByID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role actions";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no action ID specified";
            return -2;
        }
        
        $sql="START TRANSACTION";
        db_query($sql);
        
        $sql="SELECT ID FROM roleRelationship WHERE actionID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleRelationshipByID($aResult[$i]["ID"]);
        }
        
        $sql="SELECT ID FROM roleTypeRelationship WHERE actionID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleTypeRelationshipByID($aResult[$i]["ID"]);
        }
        
        $sql="SELECT ID FROM roleGlobalAction WHERE actionID='".$nID."'";
        $aResult=db_fetch_array(db_query($sql));
        
        for ($i=0; $i<count($aResult); $i++)
        {
            $this->RemoveRoleGlobalActionByID($aResult[$i]["ID"]);
        }

        //Now delete the roleAction
        $sql="DELETE FROM roleAction WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleAction",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        
        $sql="COMMIT";
        db_query($sql);
        
        return 1;
    }
    /*---------------------------------------------------------------------------------
      int RemoveRoleRelationshipByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleRelationship based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleRelationshipByID($nID)
    {
        
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role relationships";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no role relationship ID specified";
            return -2;
        }
        
        //Remove an entry from roleRelationship
        $sql="DELETE FROM roleRelationship WHERE ID='".$nID."'"; // we lacka UNIQUE KEY, so don't limit this.
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleRelationship",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        return 1;
        
    }
    
    /*---------------------------------------------------------------------------------
      int RemoveUserRelationshipByUsersAndType($sPrimaryUsername, $sSecondaryUsername, $sType)
      Created by Jesse van Herk <jesse@bioware.com> 
	March 03, 2006
      
      Description: Removes a UserRelationship based on usernames and action type
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No primary username
      -3 => No secondary username
      -4 => No action type
      ---------------------------------------------------------------------------------*/
    public function RemoveUserRelationshipByUsersAndType($sPrimaryUsername, $sSecondaryUsername, $sType)
    {
        if (!$this->IsGlobalActionAvailableToUser("manage.User.Relationships"))
        {
    	    $this->aErrors[] = "you do not have permission to remove user relationships";
            return -1;
        }
        
        if (strlen($sPrimaryUsername) < 1)
        {
    	    $this->aErrors[] = "no primary username specified";
            return -2;
        }
        if (strlen($sSecondaryUsername) < 1)
        {
    	    $this->aErrors[] = "no secondary username specified";
            return -3;
        }
        if (strlen($sType) < 1)
        {
    	    $this->aErrors[] = "no relationship type specified";
            return -4;
        }
        
	$sPrimaryUsername = trim($sPrimaryUsername);
	$sSecondaryUsername = trim($sSecondaryUsername);

        //Remove an entry from roleRelationship
        $sql = "DELETE uR FROM userRelationship AS uR
		INNER JOIN roleAction AS rA
		ON uR.actionID=rA.ID
		WHERE uR.primaryUsername='" . db_escape_string($sPrimaryUsername) . "'
		AND uR.secondaryUsername='" . db_escape_string($sSecondaryUsername) . "'
		AND rA.type='" . db_escape_string($sType) . "'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "userRelationship",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        return 1;
        
    }
    /*---------------------------------------------------------------------------------
      int RemoveUserRelationshipByID($nID)
      Created by Jesse van Herk <jesse@bioware.com> 
      August 23, 2005
      
      Description: Removes a UserRelationship based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveUserRelationshipByID($nID)
    {
        if (!$this->IsGlobalActionAvailableToUser("manage.User.Relationships"))
        {
    	    $this->aErrors[] = "you do not have permission to set role type relationships";
            return -1;
        }
        
        if ($nID < 1 || !$nID)
        {
    	    $this->aErrors[] = "no user relationship ID specified";
            return -2;
        }
        
        //Remove an entry from roleRelationship
        $sql="DELETE FROM userRelationship WHERE ID='".$nID."'"; // we lacka UNIQUE KEY, so don't limit this.
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "userRelationship",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        return 1;
        
    }
    
    /*---------------------------------------------------------------------------------
      int RemoveRoleTypeRelationshipByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleTypeRelationship based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleTypeRelationshipByID($nID)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role type relationships";
            return -1;
        }
        
        if ($nID<1 || !$nID)
        {
    	    $this->aErrors[] = "no role type relationship ID specified";
            return -2;
        }
        
        //Remove an entry from roleRelationship
        $sql="DELETE FROM roleTypeRelationship WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleTypeRelationship",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        
        return 1;
        
    }
    /*---------------------------------------------------------------------------------
      int RemoveRoleGlobalActionByID($nID)
      Created by Duleepa Wijayawardhana
      August 23, 2005
      
      Description: Removes a RoleGlobalAction based on nID
      
      Returns:
      
      -1 => Not allowed, not admin
      -2 => No ID passed in
      ---------------------------------------------------------------------------------*/
    public function RemoveRoleGlobalActionByID($nID)
    {
        //Only Super Admins may set or update roles
        if (!$this->bIsAdmin)
        {
    	    $this->aErrors[] = "you do not have permission to remove role global actions";
            return -1;
        }
        
        if ($nID<1 || !$nID)
        {
    	    $this->aErrors[] = "no role global action ID specified";
            return -2;
        }
        
        //Remove an entry from roleRelationship
        $sql="DELETE FROM roleGlobalAction WHERE ID='".$nID."'";
        $nAffectedRows=db_query($sql, array("getAffectedRows" => true));
        
        if ($nAffectedRows>0)
        {
            $aOptions=array(
                "primaryNumericID" => $nID,
                "type" => "roleGlobalAction",
                "action" => "delete",
            );
            $this->Audit->SetAudit($aOptions, "rolesystem");
        }
        return 1;
        
    }
        

    /*------------------------------------
      void clearErrors()

      Author: Jesse van Herk <jesse@bioware.com>

      Description:
	clears out the error list.  Use this when you've already encountered errors in a previous
	operation, but you don't want to see those.

      Args:

      Returns:

      -----------------------------------*/
    public function clearErrors()
    {
	$this->aErrors = array();
    }
    
    /*------------------------------------
      void clearMessages()

      Author: Jesse van Herk <jesse@bioware.com>

      Description:
      clears out the messages(warnings) list.  Use this when you've already encountered 
      warnings in a previous operation, but you don't want to see those.  

      Args:

      Returns:

      -----------------------------------*/
    public function clearMessages()
    {
	$this->aMessages = array();
    }
    
    
}

?>
